#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import xml.etree.ElementTree as ET
import hashlib
import time
import datetime

from config import etc
from utils import log
from utils import util
from config import conf
from utils.wx_utils import data_weixin
from controls import data_user_third_mysql
from controls import data_user_base_mysql
from controls import data_user_brief_mysql
from controls import data_user_ss_mysql
from controls import mongo
from utils import session_base
from utils.session_mc import BaseHandler, login
from utils.wx_utils.wx_login import wx_get_access_token, wx_get_user_info


class CgiHandler(BaseHandler):
    def get(self):
        # 获取输入参数
        signature = self.get_argument('signature', default=None)
        timestamp = self.get_argument('timestamp', default=None)
        nonce = self.get_argument('nonce', default=None)
        echostr = self.get_argument('echostr', default=None)
        if not signature or not timestamp or not nonce or not echostr:
            return
        # 自己的token
        token = data_weixin.weixin_token
        # 字典序排序
        list = [token, timestamp, nonce]
        list.sort()
        sha1 = hashlib.sha1()
        map(sha1.update, list)
        # sha1加密算法
        hashcode = sha1.hexdigest()
        # 如果是来自微信的请求，则回复echostr
        if hashcode == signature:
            self.write(echostr)
            return
        else:
            return

    def post(self):
        # 从request中获取请求文本
        rawStr = self.request.body
        # 将文本进行解析,得到请求的数据
        log.i('weixin call : %s', rawStr)
        xml = ET.fromstring(rawStr)
        fromUser = xml.find('FromUserName').text
        toUser = xml.find('ToUserName').text
        createTime = xml.find('CreateTime').text
        msgType = xml.find('MsgType').text
        if msgType == 'text':
            content = str(xml.find('Content').text)
            news_item = data_weixin.match_word(content)
            if news_item:
                res = self.render_string('weixin/weixin_reply_news.html',
                                         p_fromUser=toUser,
                                         p_toUser=fromUser,
                                         p_createTime=int(time.time()),
                                         p_items=news_item,
                                         )
                self.write(res)
                return
            reply = '鹦鹉学舌 ：' + content
            res = self.render_string('weixin/weixin_reply_text.html',
                                     p_fromUser=toUser,
                                     p_toUser=fromUser,
                                     p_createTime=int(time.time()),
                                     p_reply=reply,
                                     )
            self.write(res)
            return
        if msgType == 'event':
            event = xml.find('Event').text
            if event == 'subscribe':
                reply = data_weixin.weixin_subscribe_text
                res = self.render_string('weixin/weixin_reply_text.html',
                                         p_fromUser=toUser,
                                         p_toUser=fromUser,
                                         p_createTime=int(time.time()),
                                         p_reply=reply,
                                         )
                self.write(res)
                return
            if event == 'unsubscribe':
                self.write('')
                return
            if event == 'CLICK':
                event_key = xml.find('EventKey').text
                news_item = data_weixin.match_event(event_key)
                if news_item:
                    res = self.render_string('weixin/weixin_reply_news.html',
                                             p_fromUser=toUser,
                                             p_toUser=fromUser,
                                             p_createTime=int(time.time()),
                                             p_items=news_item,
                                             )
                    self.write(res)
                    return
        self.write('')
        return


class HomeHandler(BaseHandler):
    def get(self):
        log.i('weixin home')
        self.render("weixin/home/index.html",
                    p_url=conf.url,
                    )


class WebCallbackHandler(BaseHandler):
    def get(self):
        try:
            self.ss_idx = 0

            log.i('weixin web callback')
            code = self.get_argument('code', None)
            state = self.get_argument('state', None)

            if not code:
                log.i('not code')
                self.redirect('/weixin/home')
                return

            access_res = wx_get_access_token(code)

            if not access_res:
                log.i('access error')
                self.redirect('/weixin/home')
                return

            union_id = access_res.get('unionid', None)

            user_third = data_user_third_mysql.get_user_third_by_type_and_userkey(
                data_user_third_mysql.USER_THIRD_WX_UNION, union_id
            )

            self.plant_ssid()
            if user_third:
                # 已经登录过，直接登录
                user_base = data_user_base_mysql.get_user_base_by_userid(user_third['userid'])
                login(self, user_base, None)

                if user_base['phone']:
                    # 已绑定手机号
                    self.redirect('/web/topic/list')
                else:
                    # 未绑定手机号
                    self.redirect('/web/bind/phone')
            else:
                # 未登录过，先创建再登录
                wx_user_info = wx_get_user_info(access_res['access_token'],
                                                access_res['openid'])

                userid = mongo.count_userid()
                if not userid:
                    log.e('userid fetching error')
                    res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
                    self.write(json.dumps(res))
                    self.finish()
                    return
                if not data_user_base_mysql.add_empty_user_base_item(userid):
                    log.e('user base create error')
                    res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
                    self.write(json.dumps(res))
                    self.finish()
                    return
                if wx_user_info['sex'] == 1:
                    sex = '男'
                elif wx_user_info['sex'] == 2:
                    sex = '女'
                else:
                    sex = '保密'
                if not data_user_brief_mysql.add_user_brief_item({
                    'userid': userid,
                    'name': wx_user_info['nickname'],
                    'sex': sex,
                    'intro': '',
                    'zone': wx_user_info['nickname'] + '的空间',
                    'imglink': wx_user_info['headimgurl']
                }):
                    log.e('user info create error')
                    res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
                    self.write(json.dumps(res))
                    self.finish()
                    return
                if not data_user_third_mysql.add_user_third_item({
                    'userid': userid,
                    'type': data_user_third_mysql.USER_THIRD_WX_UNION,
                    'userkey': wx_user_info['unionid']
                }):
                    log.e('user info create error')
                    res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
                    self.write(json.dumps(res))
                    self.finish()
                    return
                log.i('new weixin user base/info created: userid=%s' % userid)

                expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
                domain = util.get_domain_from_host(self.request.host)
                self.ss_user = {
                    'ssid': self.ssid,
                    'userid': userid,
                    # 'email': '',
                    'phone': '',
                    'name': wx_user_info['nickname'],
                    'sex': wx_user_info['sex'],
                    'desc': '',
                    'headimg': wx_user_info['headimgurl'],
                    'data': None
                }
                self.ssid_hmac = session_base.generate_hmac(self.ssid)
                self.set_secure_cookie(etc.cookie_check, self.ssid, domain=domain, expires=expires)
                self.set_secure_cookie(etc.cookie_verify, self.ssid_hmac, domain=domain, expires=expires)
                self.ss_store.set(self.ssid, self.ss_user)
                data_user_ss_mysql.update_userid_by_ssid({'ssid': self.ssid, 'userid': self.ss_user['userid']})

                self.redirect('/web/bind/phone')
            log.i('login now : userid=%s , ssid=%s' % (self.ss_user['userid'], self.ssid))

        except Exception as e:
            log.exp(e)

    def post(self):
        self.write('')
        return
